<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\base\Exception;
use yii\helpers\Url;

use common\models\Util;
use common\models\WxTemplateId;

/**
 * This is the model class for table "wx_gh".
 *
 * @property string $gh_id
 * @property string $appId
 * @property string $appSecret
 * @property string $token
 * @property string $accessToken
 * @property integer $accessToken_expiresIn
 * @property string $encodingAESKey
 * @property integer $encodingMode
 * @property string $wxPayMchId
 * @property string $wxPayApiKey
 * @property integer $created_at
 * @property integer $updated_at
 */
class WxGh extends \yii\db\ActiveRecord {

    const DEFAULT_GH_ID = 'gh_8510652496c4';

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'mkt_wx_gh';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['gh_id', 'appId', 'appSecret'], 'required'],
            [['accessToken_expiresIn', 'encodingMode'], 'integer'],
            [['gh_id', 'token', 'wxPayMchId'], 'string', 'max' => 32],
            [['appId', 'appSecret', 'wxPayApiKey'], 'string', 'max' => 64],
            [['title'], 'string', 'max' => 255],
            [['encodingAESKey'], 'string', 'max' => 43],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'title' => '公众号名称',
            'gh_id' => '公众号原始ID',
            'appId' => '公众号AppID（应用ID）',
            'appSecret' => '公众号AppSecret（应用密钥）',
            'token' => 'Token（令牌）',
            'accessToken' => '访问令牌',
            'accessToken_expiresIn' => '访问令牌失效时间',
            'encodingAESKey' => 'EncodingAESKey（消息加解密密钥）',
            'encodingMode' => '消息加解密方式',
            'wxPayMchId' => '微信支付商户ID',
            'wxPayApiKey' => '微信支付API密钥',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function behaviors() {
        return [
            TimestampBehavior::className(),
        ];
    }

    public function beforeSave($insert) {
        if ($insert) {
            $this->token = Util::randomString(Util::RANDOM_NONCESTRING, 16);
            $this->encodingAESKey = Util::randomString(Util::RANDOM_NONCESTRING, 43);
        }
        if (empty($this->wxPayApiKey)) {
            $this->wxPayApiKey = Util::randomString(Util::RANDOM_NONCESTRING, 32);
        }
        return parent::beforeSave($insert);
    }

    public function getWxUser($openid, $getinfo = true) {
        $wx_user = MktUser::findOne([
             'openid' => $openid,
        ]);
        
        if (empty($wx_user)) {
            $wx_user = new MktUser([
                'gh_id' => $this->gh_id,
                'openid' => $openid,
            ]);
            $wx_user->save(false);
            $wx_user->refresh();
        }
        
        if ($getinfo && (empty($wx_user->nickname) || $wx_user->update_time < date("Y-m-d", time() - 24 * 3600))) {
            $wxapp = $this->loadWx()->getApplication();
            $arrResponse = $wxapp->user->get($openid)->toArray();            
            $wx_user->setAttributes($arrResponse);
            $wx_user->save(false);
            $wx_user->refresh();
        }
        return $wx_user;
    }

    public function loadWx($dynamicOauthCallback = true) {
        if  (!yii::$app->has('wx')) {
            yii::$app->set('wx', [
                'class' => 'common\wosotech\WX',
                'config' => [
                    'debug' => true,
                    'app_id' => $this->appId,
                    'secret' => $this->appSecret,
                    'token' => $this->token,
                    //'aes_key' => $this->encodingAESKey,
                    'log' => [
                        'level' => 'debug',
                        'file'  => (yii::$app instanceof yii\console\Application) ? './runtime/easywechat.log' : '../runtime/easywechat.log',
                    ],
                    'oauth' => [
                        'scopes' => ['snsapi_base'], // scopes: snsapi_userinfo, snsapi_base, snsapi_login
                        'callback' => $dynamicOauthCallback ? Url::current() : Url::to(['wap/callback']),
                    ],
                    'payment' => [
                        'merchant_id' => '',
                        'key' => '',
                        'cert_path' => 'path/to/your/cert.pem',
                        'key_path' => 'path/to/your/key', // XXX: absolute path！！！！
                        // 'device_info'     => '013467007045764',
                        // 'sub_app_id'      => '',
                        // 'sub_merchant_id' => '',
                        // ...
                    ],                         
                    'guzzle' => [
                        'timeout' => 5, 
                        'verify'=> false,
                    ],                                    
                ]            
            ]);  
        }
        return  yii::$app->get('wx');
    }

    static public function getDefaultGhId() {
        return WxGh::DEFAULT_GH_ID;    
    }

    static public function getDefaultGh() {
        return WxGh::findOne(['gh_id' => self::getDefaultGhId()]);    
    }

    static public function getSessionOpenid() {
        if (!empty(Yii::$app->request->get('openid'))) {
            return Yii::$app->request->get('openid');
        } else if (!empty(Yii::$app->session->get('openid'))) {
            return Yii::$app->session->get('openid');
        } else {
             $wxapp =  WxGh::getDefaultGh()->loadWx(false)->getApplication();
             $oauth = $wxapp->oauth;
             Yii::$app->session['breakpoint'] = Url::current();
             $oauth->redirect()->send();
             exit;                     
         }            
    }

    public function getTemplateId($template_id_short) {
        $templateIdModel = WxTemplateId::findOne([
                    'gh_id' => $this->gh_id,
                    'template_id_short' => $template_id_short,
        ]);
        if (empty($templateIdModel)) {
            //$responseArray = $this->apiTemplateAddTemplate($template_id_short);
            $wxapp =  $this->loadWx(false)->getApplication();
            $responseArray = $wxapp->notice->addTemplate($template_id_short);
            //yii::error(print_r($responseArray, true));
            $templateIdModel = new WxTemplateId;
            $templateIdModel->gh_id = $this->gh_id;
            $templateIdModel->template_id_short = $template_id_short;
            $templateIdModel->template_id = $responseArray['template_id'];
            $templateIdModel->save(false);
            
        }
        return $templateIdModel->template_id;
    }
    
}
